package com.powernode.driver.service.impl;


import com.powernode.common.execption.PowerException;
import com.powernode.common.result.ResultCodeEnum;
import com.powernode.driver.config.TencentProperties;
import com.powernode.driver.service.CiService;
import com.powernode.driver.service.CosService;
import com.powernode.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    @Resource
    private TencentProperties tencentProperties;


    @Resource
    private CiService ciService;

    /**
     * 上传文件
     * 1.文件重命名
     * 2.上传文件到cos中
     * 3.获取上传文件的url
     * 4.构建vo对象返回
     *
     * @param file 上传文件
     * @param path 我们自己指定的上传的文件夹
     */
    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        //获取cosClient
        COSClient cosClient = cosClient();

        //构建对象元数据 描述上传文件的元数据  文件大小  文件类型
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());//文件大小
        metadata.setContentType(file.getContentType()); //文件类型
        metadata.setContentEncoding("utf-8");

        //1.文件重命名  lyf.png
        //获取后缀名
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //拼接文件名和上传路径   /driver/idcard/adsfzxcvq45234vsadgad.png
        String uploadPath = "/driver/" + path + "/" + UUID.randomUUID().toString().replaceAll("-", "") + fileType;

        try {
            //构建上传请求对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentProperties.getBucketPrivate(), uploadPath, file.getInputStream(), metadata);
            putObjectRequest.setStorageClass(StorageClass.Standard);

            //上传文件
            cosClient.putObject(putObjectRequest);
            cosClient.shutdown();


            //审核图片
            Boolean flag = ciService.imageAuditing(uploadPath);
            if (!flag) {
                //删除违规的图片
                cosClient.deleteObject(tencentProperties.getBucketPrivate(), uploadPath);
                throw new PowerException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
            }


            //构建返回结果对象
            CosUploadVo cosUploadVo = new CosUploadVo();
            cosUploadVo.setUrl(uploadPath);

            //获取上传文件的显示地址
            cosUploadVo.setShowUrl(getImageUrl(uploadPath));

            return cosUploadVo;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /*
        获取上传文件的显示
     */
    @Override
    public String getImageUrl(String path) {
        //获取cosclient对象
        COSClient cosClient = cosClient();

        //构建请求对象
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(tencentProperties.getBucketPrivate(), path, HttpMethodName.GET);

        //设置url过期时间
        Date date = new DateTime().plusMinutes(20).toDate();

        request.setExpiration(date);

        //获取图片的访问 地址
        URL url = cosClient.generatePresignedUrl(request);

        cosClient.shutdown();

        System.out.println("身份证照片地址=====================" + url.toString());

        return url.toString();
    }

    //构建cosClient
    private COSClient cosClient() {
        //传入密钥信息
        COSCredentials cred = new BasicCOSCredentials(tencentProperties.getSecretId(), tencentProperties.getSecretKey());

        //传入桶的区域信息
        Region region = new Region(tencentProperties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        //设置https
        clientConfig.setHttpProtocol(HttpProtocol.https);

        //构建cosClient
        COSClient cosClient = new COSClient(cred, clientConfig);

        return cosClient;
    }
}
